package com.sunwayworld.basemodule.rm.train.question.validator;

import java.util.List;
import java.util.stream.Collectors;

import com.sunwayworld.basemodule.rm.train.question.bean.LimsCoreQuestionBean;
import com.sunwayworld.basemodule.rm.train.question.bean.LimsCoreQuestionOptBean;
import com.sunwayworld.basemodule.rm.train.question.service.LimsCoreQuestionOptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.framework.validator.data.DataValidator;

@Component
public class LimsCoreQuestionActivatableValidator implements DataValidator {
    @Autowired
    private LimsCoreQuestionOptService coreQuestionOptService;

    public boolean doValid(Object... args) {
        RestJsonWrapperBean warpper = (RestJsonWrapperBean) args[0];
        
        List<LimsCoreQuestionBean> questionList = warpper.parse(LimsCoreQuestionBean.class);
        
        List<LimsCoreQuestionBean> questionAnswerEmptyList = questionList.stream().filter(f -> StringUtils.isBlank(f.getAnswer())).collect(Collectors.toList());
        if (!questionAnswerEmptyList.isEmpty()) {
            questionAnswerEmptyList.forEach(e -> {
                addConstraintViolation(e.getQuestionContent() + I18nHelper.getMessage("CORE.MODULE.TRAIN.QUESTION.TIP.QUESTION_ANSWER_CANNOT_EMPTY"));
            });
            return false;
        }
        
        boolean flag = true;
        
        List<LimsCoreQuestionBean> choiceQustionList = questionList.stream().filter(f -> "singleChoice".equals(f.getQuestionType()) || "multipleChoice".equals(f.getQuestionType())).collect(Collectors.toList());
        if (!choiceQustionList.isEmpty()) {
            
            List<Long> choiceQustionIdList = choiceQustionList.stream().map(LimsCoreQuestionBean::getId).collect(Collectors.toList());
            
            List<LimsCoreQuestionOptBean> questionOptList = coreQuestionOptService.selectListByFilter(SearchFilter.instance().match("QUESTIONID", choiceQustionIdList).filter(MatchPattern.OR));
            

            for (LimsCoreQuestionBean question : choiceQustionList) {
                if (!questionOptList.stream().anyMatch(f-> f.getQuestionId().equals(question.getId()))) {
                    addConstraintViolation(question.getQuestionContent() + I18nHelper.getMessage("CORE.MODULE.TRAIN.QUESTION.TIP.QUESTION_OPT_CANNOT_EMPTY"));
                    flag = false;
                }
            }
        }
        return flag;
    }
}
